<?php

namespace Trawind\Basics;

use Trawind\Helpers\ArrHelper;
use Illuminate\Http\Response;
use League\Fractal\TransformerAbstract;
use Trawind\Basics\Enums\BusinessCode;
use Illuminate\Database\Eloquent\Model;
use Trawind\Basics\Exceptions\LogicException;
use Prettus\Repository\Presenter\FractalPresenter;

abstract class TrawindPresenter extends FractalPresenter
{

    protected $businessTypeId;


    public function present($data)
    {
        $this->businessTypeId = $data instanceof Model ? $data->businessType : $data[0]->businessType;

        $result = $this->getTransformer()->fillTransformData(parent::present($data));
        if (!is_null($view = request('view'))) {
            if (request('pageSize') !== '0') {
                throw (new LogicException('pageSize must 0', BusinessCode::PARAMETER_ERROR))
                    ->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
            }
            $transformMethod = 'transform'.ucfirst($view);
            $result = $this->{$transformMethod}($result);
        }
        return $result;
    }


    /**
     * @note 渲染树形视图
     * @param $result
     * @return array
     */
    public function transformTree($result)
    {
        $data = ArrHelper::tree($result['data']);
        if (request('isRootNode')) {
            $defaultTopNode = [
                'id' => 0,
                'parent_id' => '-1',
                'name' => ___('please_choose')
            ];
            $defaultTopNode = array_merge($defaultTopNode, $this->getTransformer()->treeTopNode());
            array_unshift($data, $defaultTopNode);
        }
        return compact('data');
    }


    /**
     * @note 渲染分组视图
     * @param $result
     * @return array
     * @throws LogicException
     */
    public function transformGroup($result)
    {
        $data = [];
        $index = request('keyBy');
        foreach ($result['data'] as $value) {
            if (!isset($value[$index])) {
                throw (new LogicException('`keyBy` is invalid', BusinessCode::PARAMETER_ERROR))
                    ->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY);
            }
            $data[$value[$index]][] = $value;
        }
        return compact('data');
    }


    final public function getTransformer()
    {
        /** @var TrawindTransformer $transformer */
        $transformer = $this->transformer();
        return $transformer::getInstance($this->businessTypeId);
    }


    abstract public function transformer(): string;

}